/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.health;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Map;

import com.mobaas.devops.HealthChecker;
import com.mobaas.devops.HealthResult;

/**
 * TCP方式health检查实现
 * @author billy zhang
 *
 */
public class TcpHealthChecker implements HealthChecker {

	@Override
	public <T extends HealthResult> T check(Map<String, Object> data) {
		String host = (String)data.get("host");
		int port = (Integer)data.get("port");
		boolean ok = false;
		try {
			
			Socket socket = new Socket();
			socket.connect(new InetSocketAddress(host, port), 5000); // 5s
			socket.close();
			
			ok = true;
			
		} catch (IOException e) {

			e.printStackTrace();
		}
		

		TcpHealthResult result = new TcpHealthResult(ok);
		return (T)result;
	}

	private class TcpHealthResult implements HealthResult {

		private boolean ok;
		
		public TcpHealthResult(boolean ok) {
			this.ok = ok;
		}
		
		@Override
		public boolean isOk() {
			return ok;
		}
		
	}
}
